<?php
###############   COPYLEFT GPLv3 LICENSE   ###############
##
## JFX Version 0.2.9
## Website Management Software
## www.jfxcms.com
##
## Copyright 2009 GPLv3 - http://www.opensource.org/licenses/gpl-3.0.html
##
## Anthony Gallon
## oi_antz@hotmail.com
##
## Permission is hereby granted to any person having a copy of this software
## to freely use and modify as required so long as the copyright notices
## and branding remain intact.
##
## Full license details available at http://www.jfxcms.com/license
##
###############   COPYLEFT GPLv3 LICENSE   ###############

$THEME->addBreadcrumb($this->adminUrl.'/modules/list/', $this->lang('ap_title_modules_list'));





JFX::checkAdminPermsRedirect('core', 'perm_manage_modules');








if(Antz_IntelliForm::submitted('upload-module')){
    if(isset($_FILES['file']) && file_exists($_FILES['file']['tmp_name'])){
        $error = false;

        $fc = file_get_contents($_FILES['file']['tmp_name']);
        $moduleParams = unserialize($fc);
        if(!is_array($moduleParams) ||
            !array_key_exists('m', $moduleParams) ||
            $moduleParams['m'] != strtolower($moduleParams['m']) ||
            preg_replace('/[^a-zA-Z0-9]/', '', $moduleParams['m']) != $moduleParams['m']){
            
            JFX::addError($this->lang('invalid_file'));
            $error = true;
        }else{
            $moduleKey = $moduleParams['m'];
        }

        $isTheme = JFX_Theme::isValidTheme($moduleKey);
        $isModule = JFX_Module::isValidModule($moduleKey);

        if((!$error) && ($isTheme && JFX_Theme::isInstalled($moduleKey) || $isModule && JFX_Module::isInstalled($moduleKey)) && (post('overwrite')!=1)){
            $error = true;
            JFX::addError($this->foldLang('module_already_installed', $moduleKey));
        }

        if(!$error){
            // now we are going to process
            if($array_key_exists('is_theme', $moduleParams) && (bool) $moduleParams['is_theme']) $dirname = $CONFIG->themesDir.'/'.$moduleKey;
            else $dirname = $CONFIG->modulesDir.'/'.$moduleKey;
            $MM = JFX::registry('JFX_Module_Manager');
            $MM->import($_FILES['file']['tmp_name'], $dirname);
            JFX::addSuccess($this->lang('module_imported_success'));
        }

    }
}













if(get('download')!=''){
    $module = get('download');
    $isModule = JFX_Module::isValidModule($module);
    $isTheme = JFX_Theme::isValidTheme($module);

    if($isTheme || $isModule){
        if($isTheme){
            $className = 'JFX_Theme_'.$module;
            $contentType = 'application/jfx-theme';
            $ext = 'jfxt';
        }else{
            $className = 'JFX_Module_'.$module;
            $contentType = 'application/jfx-module';
            $ext = 'jfxm';
        }
        $object = JFX::registry($className);
        $tmpName = $CONFIG->tmpDir.'/'.get('download').'.moduleexport.'.$ext;
        $object->saveExport($tmpName);
        
        while(ob_get_level()>0) ob_end_clean();
        header('Content-type: '.$contentType);
        header('Content-disposition: attachment; filename='.$object->keyname.'_'.$object->getVersion().'.'.$ext);
        readfile($tmpName);
        exit;
    }
}








if(get('install')!=''){
    $module = get('install');
    $isModule = JFX_Module::isValidModule($module);
    $isTheme = JFX_Theme::isValidTheme($module);

    if(!$isTheme && !$isModule){
        JFX::addError($this->lang('invalid_module'));
    }else{
        if(JFX_Module::isInstalled($module) || JFX_Theme::isInstalled($module)){
            JFX::addError($this->lang('module_already_installed'));
        }else{
            $className = ($isTheme)
                ? 'JFX_Theme_'.ucfirst(strtolower($module))
                : 'JFX_Module_'.ucfirst(strtolower($module))
                ;
            $object = JFX::registry($className);

            if(!is_object($object)){
                JFX::addError($this->lang('could_not_instantiate_module'));
                $error = true;
            }else{
                $error = false;


                // check dependencies
                $deps = $object->getDependencies();
                foreach($deps as $dep){
                    $depName = $dep['keyname'];
                    $depVersion = explode('.', $dep['version']);
                    if($DB->countRows($CONFIG->dbprefix.'modules', "keyname = '{$depName}'")==0){
                        JFX::addError($this->foldLang('requires_dependencies', $depName, implode('.', $depVersion)));
                        $error = true;
                        continue;
                    }else{
                        $version = $DB->oneValue($CONFIG->dbprefix.'modules', 'version', "keyname = '{$depName}'");
                        $version = explode('.', $version);
                        foreach($version as $k=>$v){
                            if((int) $depVersion[$k] > $version[$k]){
                                JFX::addError($this->foldLang('requires_upgraded_dependencies', $depName, implode('.', $version), implode('.', $depVersion)));
                                $error = true;
                                break;
                            }
                        }
                    }
                }

            }

            if(!$error){
            // lets install the module
            
                $dbParams = array(
                    'keyname' => $module,
                    'version' => $object->getVersion(),
                    'title' => $object->getTitle(),
                    'sorting' => (1+$DB->oneValue($CONFIG->dbprefix.'modules', 'sorting', "1 ORDER BY sorting DESC"))
                );

                $result = $object->install();

                if($isTheme){
                    $tablename = $CONFIG->dbprefix.'themes';
                }else{
                    $tablename = $CONFIG->dbprefix.'modules';
                }

                $DB->insert($tablename, $dbParams);

                $LANG->update('core', 'perm_module_admin_'.$module, 'Manage '.$object->getTitle());

                $dbParams = array(
                    'keyname' => 'perm_module_admin_'.$module,
                    'module_key' => 'core'
                );

                if($result !== false){
                    $DB->insert($CONFIG->dbprefix.'admin_permissions', $dbParams);
                    JFX::addSuccess($this->lang('module_install_success'));
                }else{
                    JFX::addError($this->lang('module_install_error'));
                }

            }
            
            JFX::redirect($CONFIG->adminUrl.'/modules/list/');
        }
    }
}


if(get('uninstall')!=''){
    $module = get('uninstall');

    if($module == $this->keyname){
        JFX::addError($this->lang('cannot_uninstall_core_module'));
        JFX::redirect($this->adminUrl.'/modules/list/');
    }
    if(!JFX_Module::isValidModule($module)){
        JFX::addError($this->lang('invalid_module'));
    }else{

        $moduleObj = JFX_Module::getInstance($module);

        if(strlen(post('confirm'))==0){
            $error = true;
            $formFields = array(
                array(
                    'type' => 'longtag',
                    'tag' => 'h2',
                    'content' => $this->foldLang('uninstall_module', $moduleObj->getTitle())
                ),
                array(
                    'type'=>'submit',
                    'name' => 'confirm',
                    'value' => $this->lang('confirm_uninstall'),
                    'label' => '&nbsp;'
                )
            );
            $form = JFX::makeRapidForm($formFields, $this->foldLang('uninstall_module', $moduleObj->getTitle()), 'uninstall-module');
            echo (string) $form;
        }else{
            // form submitted and confirmed

            if(!JFX_Module::isInstalled($module)){
                JFX::addError($this->lang('module_not_installed'));
            }else{
                // lets install the module
                $safeModule = preg_replace('/[^a-zA-Z0-9]/', '', $module);
                $object = JFX::registry('JFX_Module_'.$safeModule);
                $object->uninstall();
                $DB->delete($CONFIG->dbprefix.'modules', "keyname = '{$safeModule}'");
                $DB->delete($CONFIG->dbprefix.'admin_permissions', "keyname = 'perm_module_admin_{$safeModule}' AND module_key = 'core'");
                $DB->delete($CONFIG->dbprefix.'admin_users_to_permissions', "permission_key = 'perm_module_admin_{$safeModule}' AND module_key = 'core'");
                JFX::addSuccess($this->lang('module_uninstall_success'));
                JFX::redirect($CONFIG->adminUrl.'/modules/list/');
            }

        }
    }

}







// form to upload
$formFields = array(
    array(
        'name' => 'file',
        'value' => '',
        'type' => 'file',
        'label' => $this->lang('file')
    ),
    array(
        'name' => 'overwrite',
        'value' => 1,
        'type' => 'checkbox',
        'label' => $this->lang('overwrite_existing_files')
    ),
    array(
        'name' => 'submitBtn',
        'value' => $this->lang('submit'),
        'type' => 'submit',
        'label' => '&nbsp;'
    )
);

$form = JFX::makeRapidForm($formFields, $this->lang('upload_module_legend'), 'upload-module');

$SMARTY->assign('moduleUploadForm', (string) $form);






$installedModules = JFX_Module::getInstalledModules();
$modules = array();
$readModules = array();

foreach($installedModules as $k=>$v){
    if(array_key_exists($v['keyname'], $modules)) continue;

    $modules[] = array(
        'keyname' => $v['keyname'],
        'installed' => true,
        'canInstall' => ($this->checkPermission('perm_install_modules') && $v['keyname'] != $this->keyname),
        'object' => $v['object'],
        'title' => $v['object']->getTitle(),
        'hasAdmin' => (bool) (method_exists($v['object'], 'admin') && $USER->checkAdminPermission('core', 'perm_module_admin_'.$v['keyname']))
    );
    $readModules[$v['keyname']] = $v['keyname'];
}

$dh = opendir($CONFIG->modulesDir);
while($file = readdir($dh)){
    if($file == '..' || $file == '.' || !is_dir($CONFIG->modulesDir.'/'.$file) || !file_exists($CONFIG->modulesDir.'/'.$file.'/'.$file.'.module.php')) continue;

    if(strtolower($file) != $file){
        JFX::addError($this->foldLang('invalid_module_name_case', $file));
        continue;
    }

    if(preg_replace('/[^a-zA-Z0-9]/', '', $file) != $file){
        JFX::addError($this->foldLang('invalid_module_name_chars', $file));
        continue;
    }

    if(array_key_exists($file, $readModules)) continue;

    $count = count($modules);
    $modules[$count] = array('keyname' => $file);
    $modules[$count]['installed'] = JFX_Module::isInstalled($file);
    $modules[$count]['canInstall'] = ($this->checkPermission('perm_install_modules') && $v['keyname'] != $this->keyname);
    $obj = JFX::registry('JFX_Module_'.ucfirst(strtolower($file)));
    $modules[$count]['object'] = $obj;
    $modules[$count]['title'] = $obj->getTitle();
    $modules[$count]['hasAdmin'] = (bool) (method_exists($obj, 'admin') && $USER->checkAdminPermission('core', 'perm_module_admin_'.$file));
}



// get our themes

$themes = array();
$installedThemes = JFX_Theme::getInstalledThemes();
$readThemes = array();


foreach($installedThemes as $k=>$v){
    if(array_key_exists($v['keyname'], $themes)) continue;

    $themes[] = array(
        'keyname' => $v['keyname'],
        'installed' => true,
        'canInstall' => ($this->checkPermission('perm_install_modules') && $v['keyname'] != $SETTINGS->get('theme-admin')),
        'object' => $v['object'],
        'title' => $v['object']->getTitle(),
        'hasAdmin' => (bool) (method_exists($v['object'], 'admin') && $USER->checkAdminPermission('core', 'perm_module_admin_'.$v['keyname']))
    );
    $readThemes[$v['keyname']] = $v['keyname'];
}

/*

$dh = opendir($CONFIG->themesDir);
while($file = readdir($dh)){
    
    if($file == '..' || $file == '.' || !is_dir($CONFIG->themesDir.'/'.$file) || !file_exists($CONFIG->themesDir.'/'.$file.'/'.$file.'.theme.php')) continue;

    if(strtolower($file) != $file){
        JFX::addError($file.' is an invalid theme name: must be lowercase');
        continue;
    }

    if(preg_replace('/[^a-zA-Z0-9]/', '', $file) != $file){
        JFX::addError($file.' is an invalid theme name: must be alphanumeric');
        continue;
    }

    if(array_key_exists($file, $readThemes)) continue;

    $count = count($themes);
    $themes[$count] = array('keyname' => $file);
    $themes[$count]['installed'] = JFX_Theme::isInstalled($file);
    $obj = JFX::registry('JFX_Theme_'.ucfirst(strtolower($file)));
    $themes[$count]['object'] = $obj;
    $themes[$count]['title'] = $obj->getTitle();
    $themes[$count]['hasAdmin'] = (bool) (method_exists($obj, 'admin') && $USER->checkAdminPermission('core', 'perm_module_admin_'.$file));
}


*/








$eParams = array(
    'modules' => $modules,
    'themes' => $themes
);

JFX::hook('JFX_Core.modulesList', $eParams);

$SMARTY->assign('modules', $eParams['modules']);
$SMARTY->assign('themes', $eParams['themes']);

$content = $SMARTY->fetch($CONFIG->templatesDir.'/admin/modules/list.tpl');

echo $content;


